package com.manager;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.application.systemmanager.entity.SystemConfig;

/**
 * 
 * Copyrights 1997-2008 西安协同时光软件有限公司<br />
 * 
 * Filename:BaseDao.java<br />
 * 
 * Description:BaseDao，基础DAO，用来被继承<br />
 * 
 * Version:V0.1<br />
 * 
 * Author: peigen<br />
 * 
 * History: <br /> [ Author Date Version Content ]<br />
 * peigen 2008-07-29 V0.1 create <br />
 * 
 */
public class BaseDao extends HibernateDaoSupport implements IBaseDao {
	
	private JdbcTemplate jdbcTemplate;


	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	/**
	 * 空构造体
	 */
	public BaseDao() {
	}

	/**
	 * 删除
	 * 
	 * @see com.manager.IBaseDao#delete(com.manager.IBaseBean)
	 */
	@Override
	public void delete(IBaseBean entity) {
		this.getHibernateTemplate().delete(entity);
	}
	


	/**
	 * 删除集合里的对象
	 * @param List<IBaseBean>
	 */
	@Override
	public void deleteList(List<IBaseBean> list){
		this.getHibernateTemplate().deleteAll(list);
	}

	/**
	 * 插入
	 * 
	 * @see com.manager.IBaseDao#insert(com.manager.IBaseBean)
	 */
	@Override
	public void insert(IBaseBean entity) {
		this.getHibernateTemplate().saveOrUpdate(entity);
	}

	/**
	 * 根据主键查询
	 * 
	 * @see com.sync.IBaseDao#queryByPk(Class entity, java.lang.Long)
	 */
	@Override
	public IBaseBean queryByPk(IBaseBean entity, Long pk) {
		return (IBaseBean) this.getHibernateTemplate().get(entity.getClass(),
				pk);
	}
	
	/**
	 * 根据主键查询
	 * 
	 * @see com.sync.IBaseDao#queryByPk(Class entity, java.lang.String)
	 */
	@Override
	public IBaseBean queryByPk(IBaseBean entity, String pk) {
		return (IBaseBean) this.getHibernateTemplate().get(entity.getClass(),
				pk);
	}
	
	/**
	 * 根据主键查询
	 * 
	 * @see com.sync.IBaseDao#queryByPk(Class entity, java.lang.Long)
	 */
	@Override
	public IBaseBean queryByPk(IBaseBean entity, Integer pk) {
		return (IBaseBean) this.getHibernateTemplate().get(entity.getClass(),
				pk);
	}

	/**
	 * 查询全部
	 * 
	 * @see com.manager.IBaseDao#queryAll(IBaseBean entity)
	 */
	@Override
	public List<IBaseBean> queryAll(IBaseBean entity) {

		return this.getHibernateTemplate().loadAll(entity.getClass());
	}

	/**
	 * 根据名字查询
	 * 
	 * @see com.manager.IBaseDao#queryForList(java.lang.String,
	 *      com.manager.IBaseBean)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<IBaseBean> queryForList(String selectName, IBaseBean entity) {
		return this.getHibernateTemplate().find(selectName, entity);
	}

	/**
	 * 多参数查询
	 * 
	 * @see com.manager.IBaseDao#queryForList(java.lang.String,
	 *      java.lang.String, java.lang.String)
	 */
	@Override
	public List<IBaseBean> queryForList(String beanName,
			String strConditionName, String strCondition) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 更新实体
	 * 
	 * @see com.manager.IBaseDao#update(com.manager.IBaseBean)
	 */
	@Override
	public void update(IBaseBean entity) {
		this.getHibernateTemplate().update(entity);
	}

	/**
	 * 更新
	 * 
	 * @see com.manager.IBaseDao#update(java.lang.String,
	 *      com.manager.IBaseBean)
	 */
	@Override
	public void update(String statementName, IBaseBean entity) {
		// TODO Auto-generated method stub

	}

	/* 分页程序 */
	/**
	 * 总记录数
	 * 
	 * @return int 总记录数
	 */
	public int getSize() {

		return this.getHibernateTemplate().getMaxResults();
	}

	/**
	 * 当前页
	 * 
	 * @param pageSize
	 *            总记录数
	 * @return int 当前页
	 */
	public int getPage(int pageSize) {
		PageBean pb = new PageBean();
		pb.setCount(this.getSize(), pageSize);
		return pb.getPage();
	}

	/**
	 * 使用实体进行操作
	 * 
	 * @param entity
	 *            要查询的实体
	 * @param firstResult
	 *            开始取数据的下标
	 * @param maxResults
	 *            读取数据记录数
	 * @return List<IBaseBean> 结果集
	 */
	@SuppressWarnings("unchecked")
	public List<IBaseBean> getListForPage(final String sql,
			final int firstResult, final int maxResults) {
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(sql);
				query.setFirstResult(firstResult);
				query.setMaxResults(maxResults); 
				List list = query.list();
				return list;
			}
		});
		return list;
	}
    
	
    /**
    * TODO 描述方法的信息，详细说明方法的功能，列举输入参数、输出参数和返回值的含义  
    * @param sql
    * @return
     */
	public List<IBaseBean> getListForPage(final String sql) {
		List list = jdbcTemplate.queryForList(sql);
		return list;
	}
	
	public List<IBaseBean> getListForPage(final String sql,List args) {
		List list = jdbcTemplate.queryForList(sql,args.toArray());
		return list;
	}
	
	public List getMaxId(String tableName, String idName) {
		return this.getHibernateTemplate().find("select max("+idName+") from "+tableName);
	}
	
	public List getAid(String Archieved_time,String title) {

		String sql = "select id from Article where  title='"+title+"'";
		if(Archieved_time != null){
			sql +=" and Archieved_time='"+Archieved_time+"'";
		}
		return this.getHibernateTemplate().find(sql);
	}
	/**
	 * 获取行业列表方法 
	 * @return List<IBaseBean>
	 */
	@SuppressWarnings("unchecked")
	public List getDicProfessionCategoryList(){
		String sql = " FROM DicProfessionCategory order by sn";
		return this.getHibernateTemplate().find(sql);
	}
	
	/**
	 * 获取专家分类列表方法 
	 * @return List<IBaseBean>
	 */
	@SuppressWarnings("unchecked")
	public List getDicExpertSortList(){
		String sql = " FROM DicExpertSort where fatherIdFk = (select id FROM DicExpertSort where name = '所有')";
		return this.getHibernateTemplate().find(sql);
	}
	
	/**
	 *  说明：通过一级栏目取二级栏目名称
	 * @param columnName
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
	public List getTwoClassColumnByOneName(String onecolumnName){
		 String sql = " FROM Catalog where CPath like '"+onecolumnName+"%'";
		 return this.getHibernateTemplate().find(sql);	
	}  
	
	/**
	 * 
	 * Description: TODO  根据多个属性查询
	 * @param sql
	 * @param value
	 * @return List
	 * 
	 */
	@SuppressWarnings("unchecked")
	public List<BaseEntity> findByPropertys(String sql,Object[] value){
		return this.getHibernateTemplate().find(sql, value);
	}
	
	/**
	 * Description 使用实体进行操作
	 * 
	 * @param entity
	 *           带参sql查询的实体
	 * @param firstResult
	 *            开始取数据的下标
	 * @param maxResults
	 *            读取数据记录数
	 * @return List<IBaseBean> 结果集
	 */
	@SuppressWarnings("unchecked")
	public List getListForPage_New(final String sql,
			final int firstResult, final int maxResults,final List paramList) {
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				List list1 = null;
				try{					
					Query query = session.createQuery(sql);
					//增加参数=======================
					for(int i=0;i<paramList.size();i++){
						query.setParameter(i, paramList.get(i));
					}
					//=============================
					if(maxResults!=0){
						query.setFirstResult(firstResult);
						query.setMaxResults(maxResults); 
					}
					list1 = query.list();
				}catch(Exception e){
					System.out.println("错误信息：类：BaseDao ，方法：getListForPage_New"+e.getMessage());
				}finally{
					session.close(); 
				}
				return list1;
			}
		});
		return list;
	}	

	/**
	 * 
	 * Description: TODO  根据属性查询
	 * @param sql
	 * @param value
	 * @return List
	 * 
	 */
	@SuppressWarnings("unchecked")
	public List findByProperty(String sql,String value){
		return this.getHibernateTemplate().find(sql, value);
	}
	
	/**
	 * 
	* TODO 根据部门角色查询用户
	*  
	* @param oid
	* @param rid
	* @return
	 */
	public String getUserOrgRole(long oid, long rid){
		StringBuffer buf = new StringBuffer();

		// 返回list集合
		String valueAll = null;
		List list = null;
		buf.append("SELECT userid FROM T_ORG_USER where oid = "+oid+" and userid in(SELECT userid FROM t_role_user where rid = "+rid+")");
		Session session = this.getSession();
		try {
			Query query = session.createSQLQuery(buf.toString());
			query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
			list = query.list();
		} catch (RuntimeException re) {
			logger.error("searchAcceptance failed");
			throw re;
		} finally {
			if (session != null) {
				releaseSession(session);
			}
		}
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map map=(Map)list.get(i);
				if(valueAll==null){
					valueAll="P["+map.get("userid")+"]";
				}else{
					valueAll+="P["+map.get("userid")+"]";
				}
			}
		}
		return valueAll;
	}
	
	/**
	 * 
	* TODO 根据配置CODE 得到配置信息
	*  
	* @param code
	* @return
	 */
	public String findValueByCode(String code){
		 StringBuffer sql = new StringBuffer();
		 sql.append(" from SystemConfig t  where t.cofigCode = " + code);
		 SystemConfig systemConfig = (SystemConfig) getHibernateTemplate().find(sql.toString()).get(0);
		 return systemConfig.getConfigValue();
	}
	
	public void setParameter(Query query,List args){
		if(null != args && args.size()>0){
			for(int i=0;i<args.size();i++){
				query.setParameter(i, args.get(i));
			}
		}
	}
	
}
